package com.cxy.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cxy.dao.IUserDao;

import com.cxy.entity.SysUser;

@Service("userService")
public class UserService {

	private final int fieldNum = 4;
	private final int showNum = 15;

	@Resource
	private IUserDao userDao;

	public void add(SysUser user) {
		userDao.add(user);
	}

	public void update(SysUser user) {
		userDao.update(user);
	}

	public SysUser findByUserNameAndUserPassword(String userName,
			String userPassword) {
		List<SysUser> list = userDao.list(
				"from SysUser where user_name=? and user_password = ?",
				userName, userPassword);
		return list.get(0);

	}

	public String[][] list(int pageNum) {
		String[][] result = null;
		if (pageNum < 1) {
			return result;
		}
		List<SysUser> users = new ArrayList<SysUser>();
		int beginNum = (pageNum - 1) * showNum;
		users = userDao.find(beginNum, showNum, "select u from SysUser u,SysAward a where a.id = u.award.id", null);
		if (users.size() > 0) {
			result = new String[users.size()][fieldNum];
			for (int j = 0; j < users.size(); j++) {
				if(null!=users.get(j).getAward())	// 判断用户是否抽过奖
				buildResult(result, users, j);
			}
		}
		return result;
	}

	private void buildResult(String[][] result, List<SysUser> users, int j) {
			SysUser user = users.get(j);
			result[j][0] = String.valueOf(user.getId());
			result[j][1] = user.getUserName();
			result[j][2] = String.valueOf(user.getAward().getAwardLevel());
			result[j][3] = user.getUserTelephone();
	}

	public String[][] queryByAwardLevel(String level) {
		String[][] result = null;
		if (level.length() < 0) {
			return result;
		}
		List<SysUser> users = userDao.list("select u from SysUser u LEFT JOIN u.award a where a.id=?",
				Integer.valueOf(level));
		System.out.println(users.size());

		if (users.size() > 0) {
			result = new String[users.size()][fieldNum];
			for (int j = 0; j < users.size(); j++) {
				buildResult(result, users, j);
			}
		}
		return result;
	}
}
